<html>

<head>
    <meta charset="UTF-8">
    <title>Promise.race的应用</title>
</head>

<body>
<script>
    // promise.race 会在多个请求中，最先改变状态的请求参数返回
    let p1 = new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve('p1成功')
        }, 2000)
    })

    let p2 = new Promise((resolve, reject) => {
        setTimeout(() => {
            reject('p2失败')
        }, 1000)
    })
    const race = Promise.race([p1, p2])
    console.log(race) //p2 失败

    //使用场景 登录超时提示

    function loginRequest() {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                resolve('登录请求成功')
            }, 4000)
        })
    }

    function loginTimeOut() {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                reject('登录请求超时了')
            }, 1200)
        })
    }

    // 不论成功与失败，只看哪个promise优先执行完
    Promise.race([loginRequest(), loginTimeOut(),p1,p2])
        .then((value) => {
        console.log(value)
    }).catch((reason) => {
        console.log(reason)
    })
</script>
</body>

</html>
